import UIKit

struct ShareMaterial: Codable {
  let materialId: Int
  let materialType: Int  // 0文案+图片 1纯文案 2纯图片
  let categoryId: Int
  let text: [String]
  let imgUrls: [String]?  //素材有图片的情况，如果只能分享一张图片，数组只有一个元素
  let cardTitle: String?
  let taskId: Int
}

class MaterialView: UIView {

  let materialLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "素材"
    label.font = .systemFont(ofSize: 18, weight: .bold)
    return label
  }()

  lazy var segmentedControl: UISegmentedControl = {
    let control = UISegmentedControl(items: ["全部"])
    control.translatesAutoresizingMaskIntoConstraints = false
    control.selectedSegmentIndex = 0
    return control
  }()

  let tableView: UITableView = {
    let table = UITableView()
    table.translatesAutoresizingMaskIntoConstraints = false
    //        table.isScrollEnabled = false
    table.register(ShareCell.self, forCellReuseIdentifier: "KeyboardMaterialCell")
    table.estimatedRowHeight = 150
    table.rowHeight = UITableView.automaticDimension
    table.separatorStyle = .none
    table.layer.cornerRadius = 8
    table.layer.masksToBounds = true
    return table
  }()

  override init(frame: CGRect) {
    super.init(frame: frame)
    setupUI()
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  func configSegment(data: [Category]) {
    segmentedControl.removeAllSegments()
    data.enumerated().forEach { (index, category) in
      segmentedControl.insertSegment(withTitle: category.name, at: index, animated: false)

    }
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
      self.segmentedControl.selectedSegmentIndex = 0
      self.segmentedControl.sendActions(for: .valueChanged)
    }
  }

  private func setupUI() {
    backgroundColor = .white
    layer.cornerRadius = 8
    layer.masksToBounds = true

    addSubview(materialLabel)
    addSubview(segmentedControl)
    addSubview(tableView)

    NSLayoutConstraint.activate([
      materialLabel.topAnchor.constraint(equalTo: topAnchor, constant: 8),
      materialLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 12),

      segmentedControl.topAnchor.constraint(equalTo: materialLabel.bottomAnchor, constant: 15),
      segmentedControl.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20),
      segmentedControl.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20),

      tableView.topAnchor.constraint(equalTo: segmentedControl.bottomAnchor, constant: 20),
      tableView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8),
      tableView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8),
      tableView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -16),
    ])
  }
}

class ShareCell: UITableViewCell {

  let containerView = UIView()
  let titleLabel = UILabel()
  let shareImageView = UIImageView()
  let shareTextLabel = UILabel()
  let shareButton = UIButton(type: .system)

  var onShareButtonTapped: (() -> Void)?

  private let verticalStack = UIStackView()
  private let horizontalStack = UIStackView()

  override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    setupUI()
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  private func setupUI() {
    contentView.backgroundColor = .white
    selectionStyle = .none

    containerView.backgroundColor = .systemGray6
    containerView.layer.cornerRadius = 8
    containerView.translatesAutoresizingMaskIntoConstraints = false

    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.numberOfLines = 0
    titleLabel.font = UIFont.systemFont(ofSize: 16)

    verticalStack.axis = .vertical
    verticalStack.spacing = 8
    verticalStack.translatesAutoresizingMaskIntoConstraints = false
    //
    //        roomView.addSubview(horizontalStack)
    //
    //        NSLayoutConstraint.activate([
    //            horizontalStack.topAnchor.constraint(equalTo: roomView.topAnchor, constant: 8),
    //            horizontalStack.leadingAnchor.constraint(equalTo: roomView.leadingAnchor, constant: 8),
    //            horizontalStack.trailingAnchor.constraint(equalTo: roomView.trailingAnchor, constant: -8),
    //            horizontalStack.bottomAnchor.constraint(equalTo: roomView.bottomAnchor, constant: -8),
    //        ])

    horizontalStack.axis = .horizontal
    horizontalStack.spacing = 8
    horizontalStack.alignment = .center
    horizontalStack.translatesAutoresizingMaskIntoConstraints = false
    horizontalStack.backgroundColor = .white
    horizontalStack.layer.cornerRadius = 8
    horizontalStack.layer.masksToBounds = true
    horizontalStack.isLayoutMarginsRelativeArrangement = true
    horizontalStack.layoutMargins = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)

    shareImageView.translatesAutoresizingMaskIntoConstraints = false
    shareImageView.contentMode = .scaleAspectFill
    shareImageView.clipsToBounds = true
    shareImageView.widthAnchor.constraint(equalToConstant: 44).isActive = true
    shareImageView.heightAnchor.constraint(equalToConstant: 44).isActive = true

    shareTextLabel.numberOfLines = 2
    shareTextLabel.translatesAutoresizingMaskIntoConstraints = false
    shareTextLabel.font = UIFont.systemFont(ofSize: 16)

    shareButton.setTitle("分享", for: .normal)
    shareButton.setTitleColor(.white, for: .normal)
    shareButton.backgroundColor = .orange
    shareButton.layer.cornerRadius = 4
    shareButton.translatesAutoresizingMaskIntoConstraints = false
    shareButton.widthAnchor.constraint(equalToConstant: 56).isActive = true
    shareButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
    shareButton.addTarget(self, action: #selector(shareTapped), for: .touchUpInside)

    contentView.addSubview(containerView)
    containerView.addSubview(verticalStack)

    NSLayoutConstraint.activate([
      containerView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4),
      containerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8),
      containerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8),
      containerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4),

      verticalStack.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 8),
      verticalStack.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 8),
      verticalStack.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -8),
      verticalStack.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -8),
    ])
  }

  // 水平方向：包 shareButton
  private lazy var shareRowStack: UIStackView = {
    let stack = UIStackView(arrangedSubviews: [shareButton])
    stack.axis = .vertical
    stack.alignment = .trailing
    return stack
  }()

  func configUI(data: ShareMaterial) {
    verticalStack.arrangedSubviews.forEach { $0.removeFromSuperview() }  // 清空旧的子视图

    titleLabel.text = data.cardTitle ?? data.text.first ?? ""
    verticalStack.addArrangedSubview(titleLabel)

    if let imgUrls = data.imgUrls, let firstUrlString = imgUrls.first,
      let url = URL(string: firstUrlString)
    {
      // 有图片

      horizontalStack.arrangedSubviews.forEach { $0.removeFromSuperview() }  // 清空

      shareImageView.kf.setImage(with: url, placeholder: UIImage(named: "login_image_logo"))
      //            shareTextLabel.text = data.text.first

      horizontalStack.addArrangedSubview(shareImageView)
      horizontalStack.addArrangedSubview(shareTextLabel)
      horizontalStack.addArrangedSubview(UIView())  // 填充
      horizontalStack.addArrangedSubview(shareButton)

      verticalStack.addArrangedSubview(horizontalStack)

    } else {
      // 只有文字
      verticalStack.addArrangedSubview(shareRowStack)
    }
  }

  @objc private func shareTapped() {
    onShareButtonTapped?()
  }
}
